package com.smart.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smart.dao.BaseDao;
import com.smart.dao.MenuDao;
import com.smart.model.Menu;
import com.smart.model.MenuCond;
import com.smart.util.CollectionUtil;

/**
 * 
 * @author Sunxin
 *
 */
 
@Service
public class MenuServiceImpl extends BaseEntityService<Menu, MenuCond, Long> implements MenuService{

	@Autowired
	private MenuDao dao;
	
	@Override
	protected BaseDao<Menu, MenuCond, Long> getDao() {
		return dao;
	}
	
	public Menu getMenuTree(long rootNodeId) {
		Menu menu = dao.findOne(rootNodeId);
		getMenuTree(menu);
		
		return menu;
	}
	
	public Menu getMenuTree(String rootNodeCode) {
		Menu menu = dao.findOneBy("code", rootNodeCode);
		getMenuTree(menu);
		
		return menu;
	}
	
	/**
	 * 递归查询获得完整的菜单树
	 * @param menu
	 */
	private void getMenuTree(Menu menu) {
		if(menu==null) {
			return;
		}
		List<Menu> menus = this.findBy("parent.id", menu.getId());
		Collections.sort(menus, new Comparator<Menu>(){

			@Override
			public int compare(Menu o1, Menu o2) {
				if(o1.getSort() > o2.getSort()) {
					return -1;
				}
				else if(o1.getSort() < o2.getSort()) {
					return 1;
				}
				else {
					return 0;
				}
			}
			
		});
		if(CollectionUtil.isNotEmpty(menus)) {
			menu.setChildren(menus);
			for(Menu sub : menus) {
				getMenuTree(sub);
			}
		}
	}
	
	public List<Menu> toPlainStructure(Menu menu) {
		List<Menu> list = new ArrayList<Menu>();
		toPlainStructure(menu, list);
		return list;
	}
	
	private void toPlainStructure(Menu root, List<Menu> result) {
		if(root==null) {
			return;
		}
		result.add(root);
		List<Menu> subMenus = root.getChildren();
		//root.setChildren(null);
		if(CollectionUtil.isEmpty(subMenus)) {
			return;
		}
		for(Menu subMenu : subMenus) {
			toPlainStructure(subMenu, result);
		}
		
	}
	
}
